package repositories

import (
	"errors"
	"go_web/src/domain"
)
import "gorm.io/gorm"

type UserRepository struct {
	db *gorm.DB
}

func NewUserRepository(db *gorm.DB) UserRepository {
	return UserRepository{db: db}
}

// Create 创建用户
func (r UserRepository) Create(user *domain.User) error {
	return r.db.Create(user).Error
}

// UpdateByID 修改用户
func (r UserRepository) UpdateByID(id uint, name string) error {
	err := r.db.Exec("update user set name = ? where id = ?", name, id).Error
	return err

}

// DeleteByID 删除用户
func (r UserRepository) DeleteByID(id uint) error {
	err := r.db.Exec("delete from user where id = ?", id).Error
	return err

}

// FindByID 查询用户
func (r UserRepository) FindByID(id uint) (*domain.User, error) {
	var user domain.User
	err := r.db.First(&user, id).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &user, err
}

// FindByName 通过名称查询所有用户
func (r UserRepository) FindByName(name string) (*[]domain.User, error) {
	var user []domain.User
	err := r.db.Raw("select * from user where name like concat('%',?,'%')", name).Scan(&user).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &user, err
}
